const router=require('koa-router')();
const events=require('events');
const moment=require('moment');
const koaBody=require('koa-body')
const checkLogin=require('../middlewares/checkLogin');
const checkId=require('../middlewares/checkId');
const postTags=require('../config/config').post.tags;
const {User,Post,Comment,Archive}=require('../models/index');
const {post:postProxy}=require('../proxy/index');
const verifyPost=require('../lib/verifyPost');
const postCharacterLengthLimit=require('../config/config').characterLengthLimit.post;
const config=require('../config/config');

//话题详情
router.get('/:id',checkId(),async ctx=>{
    let {id}=ctx.params,post=await Post.findOne({_id:id}),ee=new events();
    ee.on('fail',msg=>{
        ctx.flash={error:msg};
        return ctx.redirect('/');
    });

    if(!post)return ee.emit('fail','话题不存在');

    let [author,comments]=await Promise.all([
        User.findOne({_id:post.author},{name:true,avatar:true,score:true,intro:true}),
        Comment.find({_id:{$in:post.comments}}),
    ]);

    if(!author)return ee.emit('fail','作者不存在');

    //话题作者
    post.author=author;
    //转载原始地址
    if(post.reprintFrom){
        post.origin=ctx.request.protocol+'://'+ctx.request.host+'/article/'+post.reprintFrom.toString();
    }

    let {loginUser}=ctx.session,isAuthor,canReprint,hasCollected;
    if(loginUser){
        let user=await User.findOne({_id:loginUser._id});
        isAuthor=user._id.toString()==post.author._id.toString();
        canReprint=!post.reprintUsers.some(user_id=>user_id.toString()==user._id.toString());
        hasCollected=user.collections.some(post_id=>post_id.toString()==post._id.toString());
    }

    //获取评论者的数据
    let authors=await Promise.all(comments.map(c=>User.findOne({_id:c.author},{name:true,avatar:true})));

    comments.forEach((c,i)=>{
        c.author=authors[i];
        c.isAuthor=loginUser&&loginUser._id==c.author._id.toString();
        c.upAction=loginUser&&c.ups.find(userId=>userId.toString()==loginUser._id)?'de_up':'up';
        c.upText='up'==c.upAction?'赞':'取消赞';
    });


    let [others,noReplies]=await Promise.all([
        postProxy.getList({author:post.author._id,_id:{$ne:id}},null,{limit:5}),//作者其它话题
        postProxy.getList({comments:{$size:0}},null,{limit:5})//无人回复的话题
    ]);

    await Post.update({_id:post._id},{$inc:{pv:1}});
    await ctx.render('article',{
        title:'话题详细页',
        loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error,
        post,
        author,
        comments,
        isAuthor,
        canReprint,
        hasCollected,
        postCharacterLengthLimit,
        others:others.posts,
        noReplies:noReplies.posts,
        refer:'/article/'+ctx.params.id
    });
});

//编辑
router.get('/edit/:id',checkLogin(),checkId(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session,ee=new events();
    ee.on('fail',msg=>{
        ctx.flash={error:msg};
        return ctx.redirect('back');
    });

    let post=await Post.findOne({_id:id});

    if(!post)return ee.emit('fail','话题不存在');

    if(post.author.toString()!==loginUser._id)return ee.emit('fail','无权限');

    let tags=postTags.map(t=>({
        name:t,
        checked:post.tags.includes(t)
    }));

    await ctx.render('editPost',{
        title:'编辑话题',
        success:ctx.flash.success,
        error:ctx.flash.error,
        loginUser,
        post,
        tags,
        postCharacterLengthLimit
    });
});

//保存编辑
router.post('/edit/:id',checkLogin(),checkId(),koaBody(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session,{body}=ctx.request,ee=new events();
    ee.on('invalid',msg=>{
        ctx.flash={error:msg};
        ctx.redirect('back');
    });

    let post=await Post.findOne({_id:id});
    if(!post)return ee.emit('invalid','话题不存在');
    if(post.author.toString()!==loginUser._id)return ee.emit('invalid','无权限');

    let data={
        title:body.title,
        tags:body.tags,
        intro:body.intro,
        content:body.content
    }
    let verifyPostRet=verifyPost(data);
    if(!verifyPostRet.verify)return ee.emit('invalid',verifyPostRet);

    await Post.update({_id:id},verifyPostRet.post);

    ctx.flash={success:'更新成功'};
    ctx.redirect('/article/'+id);
});

//收藏
router.post('/collect/:id',checkLogin(),checkId(),koaBody(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session,{action}=ctx.request.body,ee=new events();
    ee.on('fail',msg=>{
        ctx.body={
            code:404,
            msg
        }
    });
    ee.on('success',(msg,action)=>{
        ctx.body={
            code:200,
            msg,
            action
        }
    });

    let post=await Post.findOne({_id:id});
    if(!post)return ee.emit('fail','话题不存在');

    if('collect'==action){
        let ret=await User.update({_id:loginUser._id},{$addToSet:{collections:id}});
        if(ret&&ret.n)return ee.emit('success','收藏成功',action);
        ee.emit('fail','收藏失败',action);
    }else if('de_collect'==action){
        let ret=await User.update({_id:loginUser._id},{$pull:{collections:id}});
        if(ret&&ret.n)return ee.emit('success','取消收藏成功',action);
        ee.emit('fail','取消收藏失败',action);
    }
});

//转载
router.get('/reprint/:id',checkLogin(),checkId(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session,post=await Post.findOne({_id:id}),ee=new events();

    ee.on('fail',msg=>{
        console.log('Reprint post fail:',msg);
        ctx.flash={error:msg};
        ctx.redirect('back');
    });

    if(!post)return ee.emit('fail','话题不存在');

    if(post.reprintUsers.find(_id=>_id.toString()==loginUser._id))return ee.emit('fail','已经转载过此话题');

    let time=new Date(),archive=moment(time).format('YYYY-MM');
    let rePost=await new Post({
        title:'[转载]'+post.title,
        tags:post.tags,
        intro:post.intro,
        content:post.content,
        author:loginUser,
        reprintFrom:post._id,
        time,
        archive
    }).save();

    await Archive.update({archive},{$inc:{count:1}},{upsert:true});
    await Post.update({_id:post._id},{$push:{reprintUsers:ctx.session.loginUser._id}});
    await ctx.redirect('/article/'+rePost._id);
});


//删除
router.delete('/remove/:id',checkLogin(),checkId(),async ctx=>{
    let {id}=ctx.params,{loginUser}=ctx.session,ee=new events(),post=await Post.findOne({_id:id});
    ee.on('fail',msg=>{
        console.log('Remove post fail:',msg);
        ctx.body={
            code:500,
            error:msg
        };
    });

    if(!post)return ee.emit('fail','话题不存在');
    if(post.author.toString()!==loginUser._id)return ee.emit('fail','无权限');
    let tasks=[
        Post.remove({_id:id}),
        Comment.remove({post:id}),
        User.update({_id:loginUser._id},{$inc:{score:-config.score.post}}),
        User.update(null,{$pull:{collections:id}},{multi:true}),//删除其它用户的收藏
        Archive.update({archive:moment(post.time).format('YYYY-MM')},{$inc:{count:-1}})
    ];

    if(post.reprintFrom){//如果是转载的话题，则删除被转载话题上的'reprintUsers'数据
        let fromPost=await Post.findOne({_id:post.reprintFrom});
        if(fromPost){
            tasks.push(Post.update({_id:fromPost._id},{$pull:{reprintUsers:post.author}}));
        }
    }
    await Promise.all(tasks);
    ctx.session.loginUser.score-=config.score.post;
    ctx.body={code:200,success:'删除话题成功'};
});

module.exports=router;